package controller

import (
	"Last/model"
	"Last/utils"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
)

var jwtkey = []byte("handsome-zjy")

// 与用户有关的控制器，逻辑放在这里
func PersonalInfo(c *gin.Context) {
	db := utils.OpenConn()
	defer utils.CloseConn(db)
	var personal model.Personal
	//获取前端传过来的token
	tokenString := c.GetHeader("token")
	if tokenString == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": -4,
			"msg":  "用户未登录",
		})
		c.Abort()
		return
	}
	//解析token
	token, claims, err := ParseToken(tokenString)
	if err != nil || !token.Valid {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":  -4,
			"msg":   "token已经过期，需要重新登录",
			"error": err.Error(),
		})
		c.Abort()
		return
	}
	db.First(&personal, "account = ?", claims.Account)
	fmt.Println(personal.Account, personal.Unread)
	c.JSON(200, gin.H{
		"code":     200,
		"userInfo": personal,
	})
}
func ParseToken(tokenString string) (*jwt.Token, *model.Claims, error) {
	claims := &model.Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtkey, nil
	})
	return token, claims, err
}
